package com.sunchis.demo.service;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class GenericServiceImpl<T, ID extends Serializable> implements GenericService<T, ID> {
	private Class<T> persistentClass;	// T类对应的持久类
	private SqlSessionFactory sqlSessionFactory;
	
	@SuppressWarnings("unchecked")
	public GenericServiceImpl(){
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
							   .getActualTypeArguments()[0];
	}

	public SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}
	
	/**
	 * 使用@Resource注解用以标示SessionFactory，否则会报空指针异常，这点很重要
	 * @author XuLiang
	 * @since 2012/12/21 02:03
	 * @param sqlSessionFactory
	 */
	@Resource
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}
	
	/**
	 * 返回完全限定mapperId
	 * @param mapperId
	 * @return
	 */
	public String fullMapperId(String mapperId){
		String namespace = persistentClass.getName();
		return namespace + "." + mapperId;
	}
	
	public SqlSession session() {
		return getSqlSessionFactory().openSession();
	}
	
	@Override
	public void close() {
		session().close();
	}

	@Override
	public T findById(String mapperId, ID id) {
		T entity = null;
		try {
			// System.out.println(fullMapperId(mapperId));
			entity = session().selectOne(fullMapperId(mapperId), id);
		} finally {
			close();
		}
		return entity;
	}
	
	public List<T> getList(String mapperId, T entity){
		List<T> list = null;
		try {
			list = session().selectList(mapperId, entity);
		} finally {
			close();
		}
		return list;
	}
}
